<template>
  <el-card shadow="navar">
    <el-row :gutter="15">
      <el-form
        ref="elForm"
        :model="formData"
        :rules="rules"
        size="medium"
        label-width="120px"
      >
        <el-col :span="24">
          <el-form-item label="业务类型" prop="businessName">
            <MmvSelectButton
              :list="businessOptions"
              @change="businessChange"
            ></MmvSelectButton>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="useTypesOptions.length > 0">
          <el-form-item label="使用类型" prop="useType">
            <el-radio-group v-model.number="formData.useType">
              <el-radio
                v-for="(item, index) in dict.type.coupon_useType"
                @change="useTypeChange"
                :label="parseInt(item.value)"
                :key="index"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="formData.useType == 2">
          <el-form-item label="指定类型名称" prop="useTypeNo">
            <el-radio-group v-model="formData.useTypeNo">
              <el-radio
                v-for="(item, index) in useTypesOptions"
                @change="useTypeNoChange"
                :label="item.useTypeNo + ''"
                :key="index"
                >{{ item.useTypeName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="适用项目类型" prop="useArea">
            <el-radio-group v-model="formData.useArea">
              <el-radio
                v-for="(item, index) in dict.type.coupon_useArea"
                @change="useAreaChange"
                :label="parseInt(item.value)"
                :key="index"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="指定项目名称"
            prop="serviceItemsNo"
            v-if="formData.useArea == 2"
          >
            <el-select
              v-model="formData.serviceItemsNo"
              @change="serviceItemsNoChange"
              filterable
              multiple
              placeholder="请选择指定项目名称"
              clearable
              :style="{ width: 'calc(50% - 67px)' }"
            >
              <el-option
                v-for="item in serviceItemsOptions"
                :key="item.value"
                :label="item.value"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="总库存" prop="sendTotal">
            <el-input
              v-model.number="formData.sendTotal"
              maxlength="20"
              placeholder="请输入总库存"
              clearable
              :style="{ width: 'calc(50% - 67px)' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="优惠券名称" prop="couponName">
            <el-input
              v-model.number="formData.couponName"
              :disabled="disabled"
              placeholder="请输入优惠券名称"
              clearable
              :style="{ width: 'calc(50% - 67px)' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="适用单位类型" prop="applicableUnitType">
            <el-radio-group v-model="formData.applicableUnitType">
              <el-radio
                v-for="item in dict.type.coupon_applicableUnitType"
                @change="applicableUnitTypeChange"
                :key="item.value"
                :label="parseInt(item.value)"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="适用单位名称"
            prop="applicableUnitNo"
            v-if="formData.applicableUnitType == 2"
          >
            <el-select
              v-model="formData.applicableUnitNo"
              @change="applicableUnitNoChange"
              multiple
              filterable
              placeholder="请选择适用单位名称"
              clearable
              :style="{ width: 'calc(50% - 67px)' }"
            >
              <el-option
                v-for="item in applicableUnitOptions"
                :key="item.applicableUnitNo"
                :label="item.applicableUnit"
                :value="item.applicableUnitNo"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="发送节点" prop="distributedNodeId">
            <el-radio-group v-model="formData.distributedNodeId">
              <el-radio
                v-for="(item, index) in distributedNodeOptions"
                @change="distributedNodeIdChange"
                :key="index"
                :label="item.id"
                >{{ item.value }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="使用说明" prop="remark">
            <el-input
              v-model.trim="formData.remark"
              type="textarea"
              placeholder="请输入使用说明"
              maxlength="200"
              show-word-limit
              :autosize="{ minRows: 4, maxRows: 4 }"
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item size="large">
            <el-button @click="goBack">取消</el-button>
            <el-button type="primary" @click="submitForm" v-onceClick
              >提交</el-button
            >
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </el-card>
</template>

<script>
import {
  businessList,
  serviceItemsList,
  applicableUnitList,
  distributedNodeList,
} from '@/api/coupon/manage.js'
import { getBusinessById, putBusiness } from '@/api/coupon/business.js'

import MmvSelectButton from '../../components/mmv-select-button.vue'
export default {
  dicts: [
    'coupon_useArea',
    'coupon_useType',
    'coupon_applicableUnitType',
    'coupon_use_time_type',
  ],
  components: {
    MmvSelectButton,
  },

  data() {
    return {
      disabled: true,
      //业务类型
      businessOptions: [],
      useTypesOptions: [],
      serviceItemsOptions: [],
      applicableUnitOptions: [],
      distributedNodeOptions: [],
      formData: {
        businessId: '',
        businessName: '',
        useType: 1,
        useTypeNo: '',
        useTypeName: '',
        businessNo: '',
        useArea: 1,
        serviceItemsNo: [],
        serviceItems: [],
        sendTotal: '',
        couponName: '',
        couponId: '',
        applicableUnitType: 1,
        applicableUnitNo: [],
        applicableUnit: [],
        distributedNodeId: '',
        distributedNode: '',
        remark: '',
        activityUnit: [],
      },
      rules: {
        businessName: [
          {
            required: true,
            message: '请输入业务类型',
            trigger: 'change',
          },
        ],
        useType: [
          {
            required: true,
            message: '请选择指定条件',
            trigger: 'change',
          },
        ],
        useTypeNo: [
          {
            required: false,
            message: '请选择指定类型名称',
            trigger: 'change',
          },
        ],
        useArea: [
          {
            required: true,
            message: '请选择适用项目类型',
            trigger: 'change',
          },
        ],
        serviceItemsNo: [
          {
            required: false,
            message: '请选择指定项目名称',
            trigger: 'change',
          },
        ],
        sendTotal: [
          {
            required: true,
            message: '请输入总库存',
            trigger: 'blur',
          },
          {
            pattern: /^([1-9]\d*)$/,
            message: '只能输入正整数',
            trigger: 'blur',
          },
        ],
        couponName: [
          {
            required: true,
            message: '请输入优惠券名称',
            trigger: 'blur',
          },
        ],
        applicableUnitType: [
          {
            required: true,
            message: '请选择适用单位类型',
            trigger: 'change',
          },
        ],
        applicableUnitNo: [
          {
            required: false,
            message: '请选择适用单位名称',
            trigger: 'change',
          },
        ],
        remark: [
          {
            required: true,
            message: '请输入活动说明',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    Promise.all([this.getBusinessById()]).then(([ResultJson1]) => {
      this.getBusinessList()
    })
    this.getServiceItemsList()
    this.getApplicableUnitList()
    this.getDistributedNodeList()
  },
  methods: {
    useTypeChange(val) {
      this.$set(this.formData, 'useTypeNo', '')
      if (val == 2) {
        this.rules.useTypeNo[0].required = true
      } else {
        this.rules.useTypeNo[0].required = false
      }
      this.$forceUpdate()
    },
    useTypeNoChange(val) {
      this.formData.useTypeName = this.useTypesOptions.filter((item) => {
        return item.useTypeNo == val
      })[0].useTypeName
    },
    getBusinessList() {
      businessList().then((res) => {
        this.businessOptions = []
        res.data.map((item, index) => {
          item['type'] =
            item.businessNo == this.formData.businessNo ? 'primary' : ''
          this.businessOptions.push(item)
          if (item.businessNo == this.formData.businessNo) {
            this.useTypesOptions = item.useType
          }
        })
      })
    },
    async getServiceItemsList() {
      await serviceItemsList().then((res) => {
        this.serviceItemsOptions = res.data
      })
    },
    async getBusinessById() {
      await getBusinessById({ id: this.$route.params.id }).then((res) => {
        this.formData = res.data
        this.formData.serviceItemsNo = res.data.serviceItemsNo.split(',')
        this.formData.serviceItems = res.data.serviceItems.split(',')
        this.formData.applicableUnitNo =
          res.data.applicableUnitNo == ''
            ? []
            : res.data.applicableUnitNo.split(',')
        this.formData.applicableUnit = res.data.applicableUnit.split(',')
        this.formData.activityUnit = this.formData.applicableUnitNo.map(
          (item) => {
            return this.applicableUnitOptions.filter((e) => {
              return e.applicableUnitNo === item
            })[0]
          }
        )
        this.$set(this.formData, 'useTypeNo', res.data.useTypeNo)
        if (res.data.useType == 2) {
          this.rules.useTypeNo[0].required = true
        } else {
          this.rules.useTypeNo[0].required = false
        }
        if (res.data.applicableUnitType == '1') {
          this.rules.applicableUnitNo[0].required = false
          this.$refs['elForm'].clearValidate('applicableUnitNo')
        } else {
          this.rules.applicableUnitNo[0].required = true
        }
      })
    },
    async getApplicableUnitList() {
      await applicableUnitList().then((res) => {
        this.applicableUnitOptions = res.data
      })
    },
    async getDistributedNodeList() {
      await distributedNodeList().then((res) => {
        this.distributedNodeOptions = res.data
      })
    },
    businessChange(val) {
      this.formData.businessNo = val.businessNo
      this.formData.businessName = val.businessName
      this.businessOptions.map((item) => {
        if (item.businessNo == this.formData.businessNo) {
          this.useTypesOptions = item.useType
        }
      })
    },
    serviceItemsNoChange(val) {
      this.formData.serviceItems = val.map((item) => {
        return this.serviceItemsOptions.filter((e) => {
          return e.id === item
        })[0].value
      })
    },
    applicableUnitNoChange(val) {
      this.formData.applicableUnit = val.map((item) => {
        return this.applicableUnitOptions.filter((e) => {
          return e.applicableUnitNo === item
        })[0].applicableUnit
      })
      this.formData.activityUnit = val.map((item) => {
        return this.applicableUnitOptions.filter((e) => {
          return e.applicableUnitNo === item
        })[0]
      })
    },
    useAreaChange(val) {
      this.$set(this.formData, 'serviceItemsNo', [])
      if (val == '1') {
        this.rules.serviceItemsNo[0].required = false
        this.$refs['elForm'].clearValidate('serviceItemsNo')
      } else {
        this.rules.serviceItemsNo[0].required = true
      }
    },
    distributedNodeIdChange(val) {
      this.formData.distributedNode = this.distributedNodeOptions.filter(
        (e) => {
          return e.id == val
        }
      )[0].value
    },
    applicableUnitTypeChange(val) {
      this.$set(this.formData, 'applicableUnitNo', '')
      this.$set(this.formData, 'activityUnit', [])
      if (val == '1') {
        this.rules.applicableUnitNo[0].required = false
        this.$refs['elForm'].clearValidate('applicableUnitNo')
      } else {
        this.rules.applicableUnitNo[0].required = true
      }
    },
    submitForm() {
      this.$refs['elForm'].validate((valid) => {
        if (!valid) {
          this.$message.error('验证不通过，请检查输入')
          return
        } else {
          let params = {
            businessName: this.formData.businessName,
            businessId: this.formData.businessId,
            businessNo: this.formData.businessNo,
            useArea: this.formData.useArea,
            useType: this.formData.useType,
            useTypeNo:
              this.formData.useTypeNo != '' ? this.formData.useTypeNo : '',
            useTypeName:
              this.formData.useTypeName != '' ? this.formData.useTypeName : '',
            serviceItemsNo: this.formData.serviceItemsNo.join(','),
            serviceItems: this.formData.serviceItems.join(','),
            sendTotal: this.formData.sendTotal,
            couponName: this.formData.couponName,
            couponId: this.formData.couponId,
            applicableUnitType: this.formData.applicableUnitType,
            applicableUnitNo: this.formData.applicableUnitNo.join(','),
            applicableUnit: this.formData.applicableUnit.join(','),
            distributedNodeId: this.formData.distributedNodeId,
            distributedNode: this.formData.distributedNode,
            remark: this.formData.remark,
            activityUnit:
              this.formData.applicableUnitType == '1'
                ? this.applicableUnitOptions
                : this.formData.activityUnit,
          }
          putBusiness(params).then((res) => {
            this.$message.success(res.msg)
            this.goBack()
          })
        }
      })
    },
    goBack() {
      this.$router.go(-1) // 返回
      //关闭子页面
      this.$store.state.tagsView.visitedViews.splice(
        this.$store.state.tagsView.visitedViews.findIndex(
          (item) => item.path === this.$route.path
        ),
        1
      )
      this.$router.push(
        this.$store.state.tagsView.visitedViews[
          this.$store.state.tagsView.visitedViews.length - 1
        ].path
      )
    },
  },
}
</script>
